<template>
  <article class="media">
    <figure class="media-left image is-48x48">
      <img :src="`https://cn.gravatar.com/avatar/${comment.userId}?s=164&d=monsterid`">
    </figure>
    <div class="media-content">
      <div class="content">
        <strong>{{ comment.username }}</strong>
        <small class="ml-2">{{ comment.createTime | date }}</small>
        <!-- &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="text" v-if="(token && user.id === comment.userId) || user.roleId === 1" @click="delete_comment(comment.id)">删除</el-button> -->
        <form @submit.prevent="onSubmit">
          <el-button type="text" v-if="token" @click="reply()">回复</el-button>
          <el-button type="text" v-if="(token && user.id === comment.userId) || user.roleId === 1" @click="delete_comment(comment.id)">删除</el-button>
        </form>
          <!-- <br><br v-if="token && user.id != comment.userId"> -->
          {{ comment.content }}
          <br v-if="comment.parentId">
          <br v-if="comment.parentId">
          <div style="background-color: #eee; padding:10px" v-if="comment.parentId"><!--<strong>{{ comment.username }}</strong>：-->{{ comment.content }}</div>
          <br><br v-if="comment.parentId === null">
          <el-input
           type="textarea"
           :rows="2"
           placeholder="请输入你的回复..."
           v-model="textarea">
          </el-input>
      </div>
    </div>
  </article>
</template>

<script>
import { mapGetters } from 'vuex'
import { deleteComment , pushComment } from '@/api/comment'

export default {
  name: 'LvCommentsItem',
  computed: {
    ...mapGetters([
      'token','user'
    ])
  },
    data() {
    return {
      parent_id: '',
      textarea: '',
      isLoading: false,
    }
  },
  props: {
      comment: {
      type: Object,
      required: true,
    },
      slug: {
      type: String,
      default: null
    },
  },
  methods: {
    delete_comment(comment_id) {
        deleteComment(comment_id).then(value => {
        const { code } = value
        this.$message.success('评论删除成功')
        if (code === 200) {
          setTimeout(() => {
            this.$router.go(0)
          }, 500)
        }
      })
    },
    reply(comment_id) {
      this.onSubmit()
    },
    async onSubmit() {
      this.isLoading = true
      try {
        let postData = {}
        postData['content'] = this.textarea
        postData['topic_id'] = this.slug
        await pushComment(postData)
        this.$emit('loadComments', this.slug)
        this.$message.success('回复成功')
      } catch (e) {
        this.$buefy.toast.open({
          message: `Cannot comment this story. ${e}`,
          type: 'is-danger'
        })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>
